﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using StackExchange.Redis.Extensions.Core.Configuration;
using StackExchange.Redis.Extensions.Newtonsoft;
using System;
using System.Data;
using WebTest.Core.Entities.OrderAggregate;
using WebTest.Infrastructure.Dapper;
using WebTest.Infrastructure.Data;
using WebTest.Infrastructure.Interfaces;
using WebTest.Infrastructure.Services;

namespace WebTest.WebApi.Configuration
{
    public static class ConfigureInfrasturcture
    {
        public static IServiceCollection AddInfrasturctureService(this IServiceCollection services, IConfiguration configuration)
        {

            // order context
            services.AddDbContext<OrderContext>(options =>
            {
                options.UseMySql("Server=192.168.1.233;port=3306;database=test;uid=test01;pwd=test123456;pooling=true;CharSet=utf8mb4;SslMode=None");
                //options.UseMySql(configuration.GetConnectionString("MySql") , new MySqlServerVersion(new Version(10, 1, 40)), mysqlOptions =>
                //{
                //    mysqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                //});
            });
            services.AddDatabaseDeveloperPageExceptionFilter();

            // Dapper
            services.AddTransient<IDataAccess, DataAccess>();


            // redis cache
            services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = "127.0.0.1:6379";
                options.InstanceName = "webapi";
            });
            //services.AddDistributedRedisCache(r =>
            //{
            //    r.Configuration = configuration["Redis:ConnectionString"];
            //});

            // repository
            services.AddTransient(typeof(IRepository<>), (typeof(Repository<>)));
            services.AddTransient<IRepository<Order>, Repository<Order>>();

            return services;
        }
    }
}
